<template>
  <view>
    <view>
      <view>
        <view>
          <view class="desc">
            <text class="desc-text">请上传身份证正反面照片</text>
          </view>
          <view class="upload">
            <!-- 上传身份证正反面照片 -->
            <view class="upload-item">
              <view class="upload-front"> </view>
              <view class="upload-btn">
                <button @click="uploadFront">
                  <text v-if="!frontImage">+</text>
                  <!-- <text v-else>重新上传</text> -->
                  <image v-else :src="frontImage" mode="aspectFit"></image>
                </button>
                <text class="upload-text">上传身份证人面照片</text>
              </view>
            </view>
            <view class="upload-item">
              <view class="upload-back"> </view>
              <view class="upload-btn">
                <button @click="uploadBack">
                  <text v-if="!backImage">+</text>
                  <image v-else :src="backImage" mode="aspectFit"></image>
                </button>
                <text class="upload-text">上传身份证反面照片</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <button v-if="authStatus === 0" class="submit-btn" type="primary" @click="submitAuth">
      提交认证
    </button>
    <button v-else class="submit-btn" type="primary" @click="refresh">
      刷新
    </button>
  </view>
</template>

<script>
import { submitUserAuth,getUserInfo } from "@/api/api.js";

export default {
  data() {
    return {
      frontImage: "", // 身份证正面
      backImage: "", // 身份证反面
      projectId: "", // 项目 ID
      userId: "", // 用户 ID
      projectAppId: "", // 项目 App ID
      authStatus: 0, // 认证状态0未认证，1已认证
    };
  },
  onLoad(options) {
    this.projectId = options.projectId;
    this.userId = options.userId;
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      try {
        const res = await getUserInfo({
          userId: this.userId,
          projectId: this.projectId,
        });
        console.log("res", res)
        if (res.code === 1) {
          this.frontImage = res.data.front_image;
          this.backImage = res.data.back_image;
          this.authStatus = 1;
          // 获取用户信息成功
          this.projectAppId = res.data.project_app_id;
          console.log("projectAppId", this.projectAppId);
          
        } else if (res.code === -12) {
          //未实名认证

        } else if (res.code === -11) {
          //提交信息但是未认证
          this.frontImage = res.data.front_image;
          this.backImage = res.data.back_image;
          console.log("frontImage", this.frontImage);
          console.log("backImage", this.backImage);
          if (this.frontImage && this.backImage) {
            uni.showToast({ title: "认证中", icon: "success" });
            this.authStatus = 1;
          }
        }
      } catch (err) {
        console.log("getUserInfo", err);
        uni.showToast({ title: "网络请求失败", icon: "none" });
      }
    },
    // 上传身份证正面
    uploadFront() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          console.log(res);
          this.uploadImageToServer(res.tempFilePaths[0], (error, result) => {
            if (error) {
              console.error("上传出现错误:", error);
            } else {
              console.log("上传结果:", result);
              this.frontImage = result.data.fileUrl;
            }
          });
        },
      });
    },
    // 上传身份证反面
    uploadBack() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.uploadImageToServer(res.tempFilePaths[0], (error, result) => {
            if (error) {
              console.error("上传出现错误:", error);
            } else {
              console.log("上传结果:", result);
              this.backImage = result.data.fileUrl;
            }
          });
        },
      });
    },
    // 提交认证
    async submitAuth() {
      if (!this.frontImage || !this.backImage) {
        uni.showToast({ title: "请上传身份证正反面", icon: "none" });
        return;
      }
      try {
        const res = await submitUserAuth({
          user_id: this.userId,
          front_image: this.frontImage,
          back_image: this.backImage,
        });
        if (res.code === 1) {
          //认证成功
          uni.showToast({ title: "提交成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        } else {
          uni.showToast({ title: "认证失败", icon: "none" });
        }
      } catch (err) {
        uni.showToast({ title: "网络请求失败", icon: "none" });
      }
    },
    uploadImageToServer(filePath, callback) {
      console.log("上传图片", filePath);

      let url = process.env.VUE_APP_BASE_URL;
      console.log(url);
      uni.uploadFile({
        url: url + "/api/upload",
        filePath: filePath,
        name: "file",
        formData: {
          userId: this.userId,
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            try {
              const data = JSON.parse(uploadRes.data);
              uni.showToast({
                title: "上传成功",
                icon: "success",
              });
              callback(null, data); // 调用回调函数并传递结果
            } catch (error) {
              console.error("解析服务器响应失败", error);
              uni.showToast({
                title: "解析服务器响应失败",
                icon: "none",
              });
              callback(error, null);
            }
          } else {
            console.error("上传失败，状态码：", uploadRes.statusCode);
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
            callback(
              new Error(`上传失败，状态码：${uploadRes.statusCode}`),
              null
            );
          }
        },
        fail: (err) => {
          console.error("上传文件失败", err);
          uni.showToast({
            title: "上传文件失败",
            icon: "none",
          });
          callback(err, null);
        },
      });
    },
    refresh () {
      this.getUserInfo();
    }
    // 调用示例
  },
};
</script>

<style scoped>
.upload-item {
  margin: 20px 20px;
}
.upload-btn button {
  width: 100%;
  height: 200px;
  font-size: 100px;
  color: #b1adad; /* 修改字体颜色为红色，你可以根据需求修改颜色值 */
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 让内容水平居中 */
  align-items: center; /* 让内容垂直居中 */
}
.upload-text {
  font-size: 14px;
  color: #b1adad; /* 修改字体颜色为红色，你可以根据需求修改颜色值 */
  text-align: center; /* 让文字水平居中 */
  margin-top: 10px; /* 增加 margin-top */
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 让内容水平居中 */
  align-items: center; /* 让内容垂直居中 */
}
.desc {
  margin-top: 20px;
  text-align: center;
}
.desc-text {
  font-size: 20px;
  color: #5f5f5f; /* 修改字体颜色为红色，你可以根据需求修改颜色值 */
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 让内容水平居中 */
  align-items: center; /* 让内容垂直居中 */
}
.submit-btn {
  margin: 100px 120px 0 120px;
  /* width: 100%; */
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  background-color: #007aff;
  border-radius: 5px;
}
</style>
